import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, Spin } from 'antd';
import { 
  UserOutlined, 
  BookOutlined, 
  ShoppingCartOutlined, 
  TeamOutlined,
  RiseOutlined,
  FallOutlined
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import styles from './Dashboard.module.css';

export default function Dashboard() {
  const [loading, setLoading] = useState(true);
  const [currentUser, setCurrentUser] = useState(null);
  const [stats, setStats] = useState({
    totalStudents: 0,
    totalTeachers: 0,
    totalCourses: 0,
    totalOrders: 0,
    monthlyRevenue: 0,
    orderGrowth: 0
  });

  // 获取当前用户信息
  useEffect(() => {
    const userData = localStorage.getItem('currentUser');
    if (userData) {
      const user = JSON.parse(userData);
      setCurrentUser(user);
    }
  }, []);

  // 获取统计数据
  const fetchStats = async () => {
    try {
      setLoading(true);
      
      // 检查用户是否已登录
      const currentUser = localStorage.getItem('currentUser');
      if (!currentUser) {
        console.error('用户未登录');
        return;
      }
      
      // 获取token
      const token = localStorage.getItem('token');
      if (!token) {
        console.error('用户未登录或token已过期');
        return;
      }
      
      // 调用后端API获取统计数据
      const response = await fetch('http://localhost:3001/dashboard/stats', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      
      if (!response.ok) {
        if (response.status === 401) {
          console.error('获取统计数据失败: 认证失败');
          // 可以在这里重定向到登录页面
          return;
        }
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      
      if (result.success) {
        setStats({
          totalStudents: result.data.totalStudents,
          totalTeachers: result.data.totalTeachers,
          totalCourses: result.data.totalCourses,
          totalOrders: result.data.totalOrders,
          monthlyRevenue: result.data.monthlyRevenue,
          orderGrowth: result.data.orderGrowth
        });
      } else {
        console.error('获取统计数据失败:', result.message);
      }
    } catch (error) {
      console.error('获取统计数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStats();
  }, []);

  // 订单趋势图配置
  const getOrderTrendOption = () => ({
    title: {
      text: '订单趋势',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: {c} 单'
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value',
      name: '订单数量'
    },
    series: [{
      data: [120, 132, 101, 134, 90, 230, 210, 182, 191, 234, 290, 330],
      type: 'line',
      smooth: true,
      lineStyle: {
        color: '#1890ff',
        width: 3
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(24, 144, 255, 0.3)'
          }, {
            offset: 1, color: 'rgba(24, 144, 255, 0.1)'
          }]
        }
      }
    }]
  });

  // 收入统计图配置
  const getRevenueOption = () => ({
    title: {
      text: '月度收入统计',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: ¥{c}'
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value',
      name: '收入(元)',
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [{
      data: [15000, 18000, 22000, 25000, 28000, 32000, 35000, 38000, 42000, 45000, 48000, 52000],
      type: 'bar',
      itemStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: '#52c41a'
          }, {
            offset: 1, color: '#73d13d'
          }]
        }
      }
    }]
  });

  // 用户分布饼图配置
  const getUserDistributionOption = () => ({
    title: {
      text: '用户类型分布',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle'
    },
    series: [{
      name: '用户类型',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['60%', '50%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '18',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 1256, name: '学员', itemStyle: { color: '#1890ff' } },
        { value: 45, name: '讲师', itemStyle: { color: '#52c41a' } },
        { value: 89, name: '课程', itemStyle: { color: '#fa8c16' } }
      ]
    }]
  });

  // 课程分类统计图配置
  const getCourseCategoryOption = () => ({
    title: {
      text: '课程分类统计',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle'
    },
    series: [{
      name: '课程分类',
      type: 'pie',
      radius: '50%',
      center: ['60%', '50%'],
      data: [
        { value: 35, name: '前端开发', itemStyle: { color: '#1890ff' } },
        { value: 25, name: '后端开发', itemStyle: { color: '#52c41a' } },
        { value: 15, name: '移动开发', itemStyle: { color: '#fa8c16' } },
        { value: 10, name: '数据科学', itemStyle: { color: '#eb2f96' } },
        { value: 4, name: '其他', itemStyle: { color: '#722ed1' } }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  })

  // 订单状态分布图配置
  const getOrderStatusOption = () => ({
    title: {
      text: '订单状态分布',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle'
    },
    series: [{
      name: '订单状态',
      type: 'pie',
      radius: '50%',
      center: ['60%', '50%'],
      data: [
        { value: 1200, name: '已支付', itemStyle: { color: '#52c41a' } },
        { value: 800, name: '待支付', itemStyle: { color: '#fa8c16' } },
        { value: 200, name: '已关闭', itemStyle: { color: '#ff4d4f' } },
        { value: 141, name: '已退款', itemStyle: { color: '#8c8c8c' } }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  });

  // 判断是否为教师
  const isTeacher = currentUser?.id?.startsWith('200');

  return (
    <div className={styles.dashboardContainer}>
      <Spin spinning={loading}>
        {/* 统计卡片 */}
        <Row gutter={[16, 16]} className={styles.statsRow}>
          <Col xs={24} sm={12} lg={6}>
            <Card className={styles.statCard}>
              <Statistic
                title={isTeacher ? "我的学员数" : "总学员数"}
                value={stats.totalStudents}
                prefix={<UserOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card className={styles.statCard}>
              <Statistic
                title={isTeacher ? "我的课程数" : "总课程数"}
                value={stats.totalCourses}
                prefix={<BookOutlined />}
                valueStyle={{ color: '#fa8c16' }}
              />
            </Card>
          </Col>
          {!isTeacher && (
            <>
              <Col xs={24} sm={12} lg={6}>
                <Card className={styles.statCard}>
                  <Statistic
                    title="总讲师数"
                    value={stats.totalTeachers}
                    prefix={<TeamOutlined />}
                    valueStyle={{ color: '#52c41a' }}
                  />
                </Card>
              </Col>
              <Col xs={24} sm={12} lg={6}>
                <Card className={styles.statCard}>
                  <Statistic
                    title="总订单数"
                    value={stats.totalOrders}
                    prefix={<ShoppingCartOutlined />}
                    valueStyle={{ color: '#eb2f96' }}
                  />
                </Card>
              </Col>
            </>
          )}
          {isTeacher && (
            <>
              <Col xs={24} sm={12} lg={6}>
                <Card className={styles.statCard}>
                  <Statistic
                    title="今日排班"
                    value={0}
                    prefix={<TeamOutlined />}
                    valueStyle={{ color: '#52c41a' }}
                  />
                </Card>
              </Col>
              <Col xs={24} sm={12} lg={6}>
                <Card className={styles.statCard}>
                  <Statistic
                    title="本月课时"
                    value={0}
                    prefix={<ShoppingCartOutlined />}
                    valueStyle={{ color: '#eb2f96' }}
                  />
                </Card>
              </Col>
            </>
          )}
        </Row>

        {/* 收入统计 */}
        {!isTeacher && (
          <Row gutter={[16, 16]} className={styles.statsRow}>
            <Col xs={24} sm={12} lg={12}>
              <Card className={styles.statCard}>
                <Statistic
                  title="本月收入"
                  value={stats.monthlyRevenue}
                  prefix="¥"
                  valueStyle={{ color: '#52c41a' }}
                  suffix={
                    <span style={{ fontSize: '14px', color: '#52c41a' }}>
                      <RiseOutlined /> +{stats.orderGrowth}%
                    </span>
                  }
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} lg={12}>
              <Card className={styles.statCard}>
                <Statistic
                  title="订单增长率"
                  value={stats.orderGrowth}
                  prefix={<RiseOutlined />}
                  suffix="%"
                  valueStyle={{ color: '#52c41a' }}
                />
              </Card>
            </Col>
          </Row>
        )}
        
        {/* 教师统计 */}
        {isTeacher && (
          <Row gutter={[16, 16]} className={styles.statsRow}>
            <Col xs={24} sm={12} lg={12}>
              <Card className={styles.statCard}>
                <Statistic
                  title="本月课时费"
                  value={0}
                  prefix="¥"
                  valueStyle={{ color: '#52c41a' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} lg={12}>
              <Card className={styles.statCard}>
                <Statistic
                  title="平均评分"
                  value={4.8}
                  suffix="/5.0"
                  valueStyle={{ color: '#fa8c16' }}
                />
              </Card>
            </Col>
          </Row>
        )}

        {/* 图表区域 */}
        <Row gutter={[16, 16]} className={styles.chartsRow}>
          <Col xs={24} lg={12}>
            <Card className={styles.chartCard}>
              <ReactECharts option={getOrderTrendOption()} style={{ height: '300px' }} />
            </Card>
          </Col>
          <Col xs={24} lg={12}>
            <Card className={styles.chartCard}>
              <ReactECharts option={getRevenueOption()} style={{ height: '300px' }} />
            </Card>
          </Col>
        </Row>

        <Row gutter={[16, 16]} className={styles.chartsRow}>
          <Col xs={24} lg={8}>
            <Card className={styles.chartCard}>
              <ReactECharts option={getUserDistributionOption()} style={{ height: '300px' }} />
            </Card>
          </Col>
          <Col xs={24} lg={8}>
            <Card className={styles.chartCard}>
              <ReactECharts option={getCourseCategoryOption()} style={{ height: '300px' }} />
            </Card>
          </Col>
          <Col xs={24} lg={8}>
            <Card className={styles.chartCard}>
              <ReactECharts option={getOrderStatusOption()} style={{ height: '300px' }} />
            </Card>
          </Col>
        </Row>
      </Spin>
    </div>
  );
} 